package vitaliy.bondar.diamondcave;

import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

public class FallingGameObject extends MovingGameObject
{
	private boolean m_isKilling = false;
	private boolean m_isSideFalling = false;
	
    public FallingGameObject( GameScene scene, final GameObject.Type type, final int pX, final int pY
    		, final ITiledTextureRegion pTiledTextureRegion, VertexBufferObjectManager vbo )
    {
        super( scene, type, pX, pY, pTiledTextureRegion, vbo);
    }

    public void fall()
    {
        if (this.m_isMoving) return;

        GameObject flour = m_scene.findItemAtPosition(this.cellX(), this.cellY() + 1);
        
        if (flour instanceof LiveGameObject && m_isKilling)
        {
            ((LiveGameObject)flour).onDie();
        }
        else if (flour == null || flour == this)
        {
            this.move(Direction.DOWN);
            m_isKilling = true;
            m_isSideFalling = false;
        }
        else if (!m_isSideFalling)
        {
            boolean wasKilling = m_isKilling;
            m_isKilling = false;
            if (flour instanceof MovingGameObject && flour.m_isMoving && flour != this)
            {
                return;
            }
            GameObject roof = m_scene.findItemAtPosition(this.cellX(), this.cellY() - 1);
            if ((roof != null && roof instanceof FallingGameObject && roof.m_isMoving))
            {
                return;
            }
            
            if (wasKilling)
            {
                this.playFallSound();
            }
            this.trySideFall();
        }
    }
    
    public final boolean isKilling()
    {
    	return m_isKilling;
    }
    
    public void trySideFall()
    {
        if (m_scene.findItemAtPosition(this.cellX() - 1, this.cellY()) == null
                && m_scene.findItemAtPosition(this.cellX() - 1, this.cellY() + 1) == null)
        {
        	m_scene.setItemInPosition(cellX() - 1, cellY() + 1, this);
            this.move(Direction.LEFT);
            m_isSideFalling = true;
            return;
        }

        if (m_scene.findItemAtPosition(this.cellX() + 1, this.cellY()) == null
                && m_scene.findItemAtPosition(this.cellX() + 1, this.cellY() + 1) == null)
        {
        	m_scene.setItemInPosition(cellX() + 1, cellY() + 1, this);
            this.move(Direction.RIGHT);
            m_isSideFalling = true;
            return;
        }
    }
    
    protected void playFallSound()
    {
    }
    
    @Override
    public void move(Direction direction) 
    {
    	if (m_scene.findItemAtPosition(cellX(), cellY() + 1) == this)
    	{
    		m_scene.setItemInPosition(cellX(), cellY() + 1, null);
    	}
    	super.move(direction);
    }
}
